﻿using Newtonsoft.Json;
using SerialPort_Assistant.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace SerialPort_Assistant.Config
{
    public class AppConfigManager
    {
        public static AppConfig AppConfig { get; set; } = new AppConfig();

        #region 持久化程序运行状态
        public static async void PersistenceAppStatus()
        {
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            //char seperator = System.IO.Path.DirectorySeparatorChar;
            string persistencePath = baseDir + "\\ConfigFiles\\data.ini.json";

            string json = JsonConvert.SerializeObject(AppConfig,Formatting.Indented);
            await File.WriteAllTextAsync(persistencePath,json);
        }
        #endregion

        #region 恢复程序之前的运行状态
        public static void RestoreAppStatus(MainViewModel viewModel)
        {
            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            //char seperator = System.IO.Path.DirectorySeparatorChar;
            string persistencePath = baseDir + "\\ConfigFiles\\data.ini.json";

            if (!File.Exists(persistencePath))
            {
                return;
            }

            try
            {
                string json = File.ReadAllText(persistencePath);
                AppConfig? appConfig = JsonConvert.DeserializeObject<AppConfig>(json);
                if (appConfig == null) return;
                appConfig.LoadAppConfig(viewModel);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        #endregion
    }
}
